<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<!-- 参考微信公众号 { -->
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0,viewport-fit=cover">
<link rel="shortcut icon" type="image/x-icon" href="//res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico">
<link rel="mask-icon" href="//res.wx.qq.com/a/wx_fed/assets/res/MjliNWVm.svg" color="#4C4C4C">
<link rel="apple-touch-icon-precomposed" href="//res.wx.qq.com/a/wx_fed/assets/res/OTE0YTAw.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<!-- } -->
<meta name="robots" content="none">
<title>IT</title>
<link href="//cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet">
<link th:href="'/webim/chatroom/ChatRoom.css?' + ${moduleVersion}" rel="stylesheet">
<link href="//cdn.bootcdn.net/ajax/libs/material-design-iconic-font/2.2.0/css/material-design-iconic-font.min.css" rel="stylesheet">
<!-- JavaScript Bundle with Popper -->
<script src="//cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
<script src="//cdn.jsdelivr.net/npm/vue@2"></script>
<script src="//cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="//cdn.bootcdn.net/ajax/libs/qs/6.10.1/qs.js"></script>
<script th:src="'/webim/common/js/common.js?' + ${moduleVersion}"></script>
<script th:src="'/webim/chatroom/ChatRoom.js?' + ${moduleVersion}"></script>
</head>

<body style="background-color: #EAEAEF;">
  <div id="app" style="height: 100%;">
    <div id="layout" class="theme-cyan">
      <div class="main">
        <div class="chat-body">
          <div class="chat-content" id="chatContent" :style="{backgroundImage: `url(/webim/common/images/background/${chineseDate}.png)`, backgroundColor: '#DCE2F1', backgroundRepeat: 'no-repeat', backgroundPosition: 'center center', backgroundSize:'100%'}">
            <div class="container-xxl">
              <ul class="list-unstyled py-4">
                <template v-for="item in messageList" :key="item.id">
                  <li class="d-flex message right" v-if="userId == item.sid">

                    <div class="message-body">
                      <span class="date-time text-muted" v-if="isShowTime(item.ctime)">{{ showTime(item.ctime) }}</span>
                      <div class="message-row d-flex align-items-center justify-content-end">
                        <div class="message-content border p-3" style="background-color: #98e165">{{ item.msg }}</div>
                      </div>
                    </div>
                  </li>
                  <li class="d-flex message" v-else>

                    <div class="message-body">
                      <span class="date-time text-muted" v-if="isShowTime(item.ctime)">{{ showTime(item.ctime) }}</span>
                      <div class="message-row d-flex align-items-center">
                        <div class="message-content p-3" style="background-color: #ffffff">{{ item.msg }}</div>
                      </div>
                    </div>
                  </li>
                </template>
                <li class="d-flex message right" v-for="item in tempMessageList">

                  <div class="message-body">
                    <div class="message-row d-flex align-items-center justify-content-end">
                      <div class="spinner-border spinner-border-sm" role="status" style="margin-right: 5px">
                        <span class="visually-hidden">Loading...</span>
                      </div>
                      <div class="message-content border p-3" style="background-color: #f9d506">
                        {{ item.message }}
                      </div>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
          <div class="chat-footer">
            <div class="container-xxl">
              <div class="row">
                <div class="col-12" style="padding-right: 0px; padding-left: 5px">
                  <div class="input-group align-items-center">
                    <input type="text" class="form-control pl-0" th:placeholder="v + ${moduleVersion}" v-model="message" v-on:keyup.enter="onClickSendButton()">
                    <div class="input-group-append">
                      <span class="input-group-text border-0 pr-0" style="padding: 5px">
                        <button type="button" class="btn btn-primary" v-on:click="onClickSendButton()">
                          <i class="zmdi zmdi-mail-send"></i>
                        </button>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

</html>

<script>
  var app = new Vue({
    el: '#app',
    data: {
      lastMessageId: 0,
      message: '',
      messageList: [],
      tempMessageId: 0,
      tempMessageList: []
    },
    computed: {
      userId: function() {
        return user.getId();
      },
      chineseDate: function() {
        var dateString = new Date().toLocaleString('zh-CN-u-ca-chinese');
        return dateString.substring(5, dateString.indexOf(' '));
      },
    },
    created: function() {
      /* 方案一：短轮询
      chatRoomService.init().then(data => {
              this.setLastMessageId(data);
              this.messageList = data;
              this.scrollToBottom(data);
          });

      // 定时刷新消息
      var intervalTime = 15 * 60 * 1000; // 15 分钟
      if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
        intervalTime = 10 * 1000; // 10 秒
      }
      setInterval(() => {
        chatRoomService.getNewestMessages(this.lastMessageId).then(data => {
                this.setLastMessageId(data);
                if (data) {
                  data.forEach(msg => {
                      this.messageList.push(msg);
                  })
                  this.scrollToBottom(data);
                }
        });
      }, intervalTime);
      */

      // 方案二：长轮询
      var getNewestMessagesAsync = () => {
        chatRoomService.getNewestMessagesAsync(this.lastMessageId).then(data => {
          if (document.visibilityState === 'hidden' && this.lastMessageId > 0 && data) {
            document.title = "有新的消息 *";
          }
          this.setLastMessageId(data);
          this.tempMessageList = this.tempMessageList.filter(item => item.id > this.lastMessageId);
          if (data) {
            data.forEach(msg => {
                this.messageList.push(msg);
            });
            this.scrollToBottom(data);
          }
          setTimeout(() => {
            getNewestMessagesAsync();
          }, 3000);
        }).catch((resp) => {
          if (resp && resp.status == 401) {
            return;
          } else {
            setTimeout(() => {
              getNewestMessagesAsync();
            }, 10000);
          }
        });
      }
      fpPromise
        .then(fp => fp.get())
        .then(result => {
          // 每次都更新
          user.visitorId = result.visitorId;
          console.log(user.visitorId);
          getNewestMessagesAsync();
        });

      document.addEventListener('visibilitychange', () => {
        if (document.visibilityState === 'visible') {
            document.title = "IT";
        }
      });
    },
    methods: {
        onClickSendButton: function () {
          const message = this.message;
          this.message = "";
            if (!message || message === '') {
                return;
            }
            const messageBody = { message };
            this.tempMessageList.push(messageBody)
            chatRoomService.sendMessage(message, this.lastMessageId).then(data => {
                messageBody.id = data;
                this.scrollToBottom(this.tempMessageList);
            });
        },
        setLastMessageId: function(messageList) {
          if (messageList) {
            const that = this;
            messageList.forEach(msg => {
              if (msg.id > that.lastMessageId) {
                that.lastMessageId = msg.id;
              }
            });
          }
        },
        // 如果有新的消息，滚动到聊天框的底部
        scrollToBottom: function(data) {
          if (!data || data.length == 0) {
            return;
          }
          setTimeout(() => {
            var chatContent = this.$el.querySelector("#chatContent");
            chatContent.scrollTop = chatContent.scrollHeight;
          });
        },
        isShowTime(time) {
          var currentTime = (new Date()).getTime();
          var date = new Date(time);
          var showString = this.padZero(date.getHours()) + ":" + this.padZero(date.getMinutes());
          // 半小时以内，不显示时间，其他的显示
          return (currentTime - time > 1800000);
        },
        showTime(time) {
          var currentTime = (new Date()).getTime();
          var date = new Date(time);
          var showString = this.padZero(date.getHours()) + ":" + this.padZero(date.getMinutes());
          // 12 小时以内，只显示时间，其他的显示日期
          if (currentTime - time > 43200000) {
            showString = date.getFullYear() + "-" + this.padZero(date.getMonth() + 1) + "-" + this.padZero(date.getDate()) + " " + showString;
          }
          return showString;
        },
        padZero: function (value) {
          if (value <= 9) {
            return "0" + value;
          } else {
            return value;
          }
        }
    }
  });
</script>